package com.party.business.service.impl;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbga.xunpay.model.PayOrderCreateReqModel;
import com.hbga.xunpay.model.PayOrderQueryResModel;
import com.party.business.domain.Kc;
import com.party.business.domain.KcType;
import com.party.business.domain.TOrder;
import com.party.business.mapper.KcMapper;
import com.party.business.mapper.KcTypeMapper;
import com.party.business.mapper.TOrderMapper;
import com.party.business.service.ITOrderService;
import com.party.common.core.domain.entity.SysUser;
import com.party.common.utils.DateUtils;
import com.party.common.utils.SecurityUtils;
import com.party.common.utils.uuid.IdUtils;
import com.party.course.domain.*;
import com.party.course.eumn.OrderState;
import com.party.course.mapper.*;
import com.party.course.service.IBearInfoService;
import com.party.course.service.IPayReqInfoService;
import com.party.course.service.IStudentChangeInfoService;
import com.party.course.util.SendQWmsgUtil;
import com.party.pay.wxpay.OrderStatus;
import com.party.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-04
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements ITOrderService {
    @Resource
    private TOrderMapper tOrderMapper;
    @Resource
    private IBearInfoService bearInfoService;
    @Resource
    private IStudentChangeInfoService studentChangeInfoService;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private UserUniteInfoMapper userUniteInfoMapper;
    @Resource
    private KcMapper kcMapper;
    @Resource
    private KcTypeMapper kcTypeMapper;
    @Resource
    private StudentInfoMapper studentInfoMapper;
    @Resource
    private DispatchInfoMapper dispatchInfoMapper;
    @Resource
    private PayGroupMapper payGroupMapper;
    @Resource
    private IPayReqInfoService payReqInfoService;


    @Resource
    private CoachInfoMapper coachInfoMapper;
    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public TOrder selectTOrderById(String id) {
        return tOrderMapper.selectTOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param tOrder 订单
     * @return 订单
     */
    @Override
    public List<TOrder> selectTOrderList(TOrder tOrder) {
        return tOrderMapper.selectTOrderList(tOrder);
    }


    @Override
    public List<TOrder> selectTOrderListss(TOrder tOrder) {
        List<TOrder> tOrders = tOrderMapper.selectTOrderList(tOrder);
        for (TOrder order : tOrders) {
            StudentInfo stu = studentInfoMapper.findByOrderCode(order.getOrderNo());
            order.setStudentInfo(stu);
            if(stu!=null){
                String coachId = stu.getCoachId();
                CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(coachId);
                if(coachInfo!=null){
                    SysUser user = sysUserMapper.selectUserById(Long.parseLong(coachInfo.getCreateBy()));
                    // 设置用户编码和用户名称
                    order.setPaCenterName(user==null?"":user.getUserName());
                    order.setCoachInfoName(coachInfo.getName());
                }


            }

        }
        return tOrders;
    }
    @Override
    public List<TOrder> selectTOrderListApp(TOrder tOrder) {
        return tOrderMapper.selectTOrderListApp(tOrder);
    }


    @Override
    public List<TOrder> selectTOrderListKcApp(TOrder tOrder) {
        return tOrderMapper.selectTOrderListKcApp(tOrder);
    }

    /**
     * 新增订单
     *
     * @param tOrder 订单
     * @return 结果
     */
    @Override
    public int insertTOrder(TOrder tOrder) {
        tOrder.setCreateTime(DateUtils.getNowDate());
        return tOrderMapper.insertTOrder(tOrder);
    }

    /**
     * 修改订单
     *
     * @param tOrder 订单
     * @return 结果
     */
    @Override
    public int updateTOrder(TOrder tOrder) {
        tOrder.setUpdateTime(DateUtils.getNowDate());
        return tOrderMapper.updateTOrder(tOrder);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteTOrderByIds(String[] ids) {
        return tOrderMapper.deleteTOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteTOrderById(String id) {
        return tOrderMapper.deleteTOrderById(id);
    }

    @Override
    @Transactional
    public String callbackPay(PayOrderQueryResModel model){
        System.out.println("下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调下单回调");
        System.out.println(JSON.toJSONString(model));
        String result = "";
        PayReqInfo reqInfo = PayReqInfo.builder()
                .id(IdUtil.simpleUUID())
                .orderNo(model.getMchOrderNo())
                .payOrderId(model.getPayOrderId())
                .reqUrl("/kcsm/webApi/callbackPay")
                .type("7")
                .param("回调参数："+JSON.toJSONString(model))
                .build();
        try {
            if (StrUtil.isNotEmpty(model.getMchOrderNo())&& ObjectUtil.isNotEmpty(model.getState())){
                TOrder order = tOrderMapper.findByOrderNo(model.getMchOrderNo());
                if (StrUtil.isNotEmpty(order.getOrderStatus()) && OrderStatus.NOTPAY.getType().equals(order.getOrderStatus())){
                    if (model.getState() == 2){
                        //支付成功
                        order.setOrderStatus(OrderStatus.SUCCESS.getType());
                        createStudent(order);
                        tOrderMapper.updateOrderStatus(model.getMchOrderNo(), OrderStatus.SUCCESS.getType());;
                    }else if (model.getState()==4){
                        //已撤销
                        tOrderMapper.updateOrderStatus(model.getMchOrderNo(), OrderStatus.CANCEL.getType());
                    }else if (model.getState()==6){
                        //订单关闭
                        tOrderMapper.updateOrderStatus(model.getMchOrderNo(), OrderStatus.CLOSED.getType());
                    }else {
                        //未支付
                        tOrderMapper.updateOrderStatus(model.getMchOrderNo(), OrderStatus.NOTPAY.getType());
                    }
                }
                result = "success";
            }else {
                result = "error";
            }
            reqInfo.setRepData("success");
            payReqInfoService.add(reqInfo);
            return result;
        }catch (Exception e){
            reqInfo.setRepData(e.getMessage());
            payReqInfoService.add(reqInfo);
            e.printStackTrace();
            return e.getMessage();
        }
    }


    /**
     * 根据订单信息生成学员信息
     *
     * @param orderInfo
     */
    @Transactional
    public void createStudent(TOrder orderInfo) {
        try {
            log.warn(orderInfo.toString());
            // 根据订单信息中的用户ID查询学员信息
            StudentInfo student = studentInfoMapper.findByUserIdAndPro(orderInfo.getUserId(), orderInfo.getProductId(), orderInfo.getOrderNo());
            if (ObjectUtil.isEmpty(student)) {
                student = new StudentInfo();
            }
            //查询课程信息
            Kc kc = kcMapper.selectKcById(orderInfo.getProductId());
            // 查询用户信息
            SysUser user = sysUserMapper.selectUserById(Long.parseLong(orderInfo.getUserId()));
            //派单
            DispatchInfo dispatch = createDispatch(orderInfo, kc.getIsTy(), orderInfo.getTjPersonPhone());
            if (dispatch != null) {
                student.setDispatchTime(dispatch.getDisTime());
                student.setDispatchRemark(dispatch.getRemark());
                // 如果学员信息为空，则创建新的学员信息
                if (ObjectUtil.isEmpty(student)) {
                    student = new StudentInfo();
                    student.setIsNew("0");
                } else {
                    // 如果学员信息不为空，则设置学员信息为已存在
                    student.setIsNew("1");
                }
                // 设置学员信息中的用户ID、订单号、支付金额、等级
                student.setName(orderInfo.getName());
                student.setRemark(orderInfo.getRemark());
                student.setUserId(orderInfo.getUserId());
                student.setOrderCode(orderInfo.getOrderNo());
                student.setPayAmount(new BigDecimal(orderInfo.getTotalFee()));
                student.setLevel(orderInfo.getGrade());
                student.setTeachSection(orderInfo.getTeachSection());
                student.setLinkPhone(orderInfo.getLinkPhone());
                student.setJcVersion(orderInfo.getJcVersion());
                student.setPhone(user.getPhonenumber());
                // 如果订单状态为支付成功，则设置学员信息为已支付
                if (StrUtil.isNotEmpty(orderInfo.getOrderStatus()) && "支付成功".equals(orderInfo.getOrderStatus())) {
                    student.setIsPay("1");
                } else {
                    // 否则设置学员信息为未支付
                    student.setIsPay("0");
                }
                // 根据订单信息中的用户ID查询用户信息
                // 如果用户信息不为空，则设置学员信息中的用户信息
                student.setCode(user.getCode());
                student.setSex(user.getSex());
                // 如果订单信息中的推荐人手机号不为空，则设置学员信息中的推荐人信息
                if (StrUtil.isNotEmpty(orderInfo.getTjPersonPhone())) {
                    student.setRecName(orderInfo.getTjPerson());
                    student.setRecPhone(orderInfo.getTjPersonPhone());
                    SysUser sysUser = sysUserMapper.findByPhone(orderInfo.getTjPersonPhone());
                    if (ObjectUtil.isNotEmpty(sysUser)) {
                        student.setStoreUserId(sysUser.getUserId().toString());
                        student.setStoreCode(sysUser.getCode());
                        student.setStoreName(sysUser.getUserName());
                    }
                }
                // 如果订单信息中的产品ID不为空，则设置学员信息中的产品信息
                student.setBuyLearnTime(kc.getKs().toString());
                student.setPayLearnTime("0");
                student.setRetreatLearnTime("0");
                student.setSurplusLearnTime(kc.getKs().toString());
                student.setClassId(kc.getId());
                student.setClassName(kc.getTitle());
                student.setClassTypeId(kc.getKcType());
                student.setTeachSection(kc.getTeachSection());
                student.setClassLevel(kc.getClassLevel());
                if ("1".equals(kc.getIsTy())) {
                    //体验课
                    student.setIsTest("0");
                } else if ("2".equals(kc.getIsTy())) {
                    //正式课
                    student.setIsTest("1");
                }
                // 根据产品信息中的产品类型ID查询产品类型信息
                KcType kcType = kcTypeMapper.selectKcTypeById(kc.getKcType());
                // 如果产品类型信息不为空，则设置学员信息中的产品类型名称
                if (ObjectUtil.isNotEmpty(kcType)) {
                    student.setClassTypeName(kcType.getName());
                }

                // 设置学员信息中的期望上课时间
                student.setExpectTime(orderInfo.getQwskDate());
                student.setCoachOrderStatus("0");
                student.setIsAddGroup("1");
                PayGroup payGroup = new PayGroup();
                if (StrUtil.isNotEmpty(dispatch.getPayGroupId())) {
                    //派单成功-有交付小组
                    student.setPayGroupId(dispatch.getPayGroupId());
                    //发送企微群消息
                    payGroup = payGroupMapper.selectPayGroupById(dispatch.getPayGroupId());
                }
                // 如果学员信息中的ID不为空，则更新学员信息
                if (StrUtil.isNotEmpty(student.getId())) {
                    studentInfoMapper.updateById(student);
                } else {
                    // 否则插入新的学员信息
                    student.setId(IdUtils.simpleUUID());
                    student.setDelFlag("0");
                    student.setSurplusAmount(new BigDecimal("0"));
                    student.setCoachOrderStatus("0");
                    student.setOrderStatus("0");
                    student.setApprovalStatus("0");
                    studentInfoMapper.insert(student);
                }
                //支付成功 向企微发送接单消息
                if (ObjectUtil.isNotEmpty(payGroup) && StrUtil.isNotEmpty(payGroup.getBotKey()) && ObjectUtil.isNotEmpty(student) && StrUtil.isNotEmpty(student.getId())) {
                    SendQWmsgUtil.sendMsg(student, payGroup.getBotKey());
                }
                //下单 新增课程变动信息
                studentChangeInfoService.add(StudentChangeInfo.builder()
                        .orderCode(student.getOrderCode())
                        .stuId(student.getId())
                        .stuCode(student.getCode())
                        .stuName(student.getName())
                        .tyep("1")
                        .genre("0")
                        .beforTimeNum("0")
                        .changeTimeNum(student.getBuyLearnTime())
                        .afterTimeNum(student.getBuyLearnTime())
                        .datil("学员下单购买课程")
                        .build());
                //计算使用的承担量
                bearInfoService.subBear(dispatch.getBearInfo(), kc.getIsTy());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成系统自动派单的派单记录
     *
     * @param orderInfo
     */
    @Transactional
    public DispatchInfo createDispatch(TOrder orderInfo, String isTest, String phone) {
        try {
            List<DispatchInfo> dispatchInfos = dispatchInfoMapper.findByProduct(orderInfo.getOrderNo());
            if (!dispatchInfos.isEmpty()) {
                return dispatchInfos.get(0);
            }
            // 创建一个DispatchInfo对象
            DispatchInfo dispatch = new DispatchInfo();
            dispatch.setId(IdUtil.simpleUUID());
            dispatch.setDelFlag("0");
//            dispatch.setCreateBy(SecurityUtils.getUserIdStr());
            // 设置订单编号
            dispatch.setClassId(orderInfo.getProductId());
            dispatch.setOrderCode(orderInfo.getOrderNo());
            // 设置派单时间
            dispatch.setDisTime(DateUtil.now());
            // 设置中心ID
            dispatch.setCenterId("0");
            // 设置中心名称
            dispatch.setCenterName("总部交付中心");
            // 设置备注
            dispatch.setRemark("交付中心直属门店派单");
            // 将派单信息插入数据库
            dispatchInfoMapper.insert(dispatch);

            //交付中心列表
            HashSet<SysUser> userList = new HashSet<>();
            //根据下单时的推荐人 判断是否存在合伙人 并进行合伙人的自动派单
            SysUser sysUser = sysUserMapper.findByPhone(phone);
            if (ObjectUtil.isNotEmpty(sysUser)) {
                //推荐人就是合伙人  超级俱乐部以及合伙人都可以开合伙人账号
                //那么推荐人的创建人就是超级俱乐部 根据超级俱乐部id查询所绑定的所有交付中心
                if (StrUtil.isNotEmpty(sysUser.getIsClubAdd())) {
                    String clubId = recursionUsers(sysUser);
                    //据超级俱乐部id查询所绑定的所有交付中心
                    List<SysUser> users = userUniteInfoMapper.findByClub(clubId);
                    if (!users.isEmpty()) {
                        userList.addAll(users);
                    }
                }
            }
            if (userList.isEmpty()) {
                // 查询角色为"交付中心"的用户列表
                userList.addAll(sysUserMapper.findByRoleName("交付中心"));
            }
            // 查询可用交付小组
            BearInfo useBear = bearInfoService.findUseBear(userList, orderInfo.getQwskDate(), isTest);
            // 如果没有可用交付小组
            if (ObjectUtil.isEmpty(useBear)) {
                // 创建一个新的DispatchInfo对象
                DispatchInfo dispatch1 = new DispatchInfo();
                dispatch1.setId(IdUtil.simpleUUID());
                dispatch1.setDelFlag("0");
//                dispatch1.setCreateBy(SecurityUtils.getUserIdStr());
                // 设置订单编号
                dispatch1.setClassId(orderInfo.getProductId());
                dispatch1.setOrderCode(orderInfo.getOrderNo());
                // 设置派单时间
                dispatch1.setDisTime(DateUtil.now());
                // 设置中心ID
                dispatch1.setCenterId("0");
                // 设置中心名称
                dispatch1.setCenterName("总部交付中心");
                // 设置备注
                dispatch1.setRemark("无可用交付小组");
                // 将派单信息插入数据库
                dispatchInfoMapper.insert(dispatch1);
                return dispatch1;
            } else {
                // 创建一个新的DispatchInfo对象
                DispatchInfo dispatch1 = new DispatchInfo();
                dispatch1.setId(IdUtil.simpleUUID());
                dispatch1.setDelFlag("0");
//                dispatch1.setCreateBy(SecurityUtils.getUserIdStr());
                // 设置订单编号
                dispatch1.setClassId(orderInfo.getProductId());
                dispatch1.setOrderCode(orderInfo.getOrderNo());
                // 设置派单时间
                dispatch1.setDisTime(DateUtil.now());
                // 设置中心ID
                dispatch1.setCenterId(useBear.getCreateBy());
                // 根据ID查询用户信息
                SysUser user = sysUserMapper.selectUserById(Long.parseLong(useBear.getCreateBy()));
                // 设置中心名称
                dispatch1.setCenterName(user.getUserName());
                // 设置支付小组ID
                dispatch1.setPayGroupId(useBear.getPayGroup().getId());
                // 设置支付小组名称
                dispatch1.setPayGroupName(useBear.getPayGroup().getName());
                // 设置备注
                dispatch1.setRemark("交付中心自动派单");
                // 将派单信息插入数据库
                dispatchInfoMapper.insert(dispatch1);
                dispatch1.setBearInfo(useBear);
                return dispatch1;
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    /**
     * 递归查询超级俱乐部id
     *
     * @param user
     * @return
     */
    public String recursionUsers(SysUser user) {
        if ("0".equals(user.getIsClubAdd())) {
            //是超级俱乐部开账号 返回超级俱乐部id
            return user.getCreateBy();
        } else {
            //不是超级俱乐部开账号 查找超级俱乐部id
            SysUser user1 = sysUserMapper.selectUserById(Long.parseLong(user.getCreateBy()));
            return recursionUsers(user1);
        }
    }

}
